<style lang="scss" scoped>
  .container {
    padding: 0 16px;
  }
  .upload-demo {
    width: 100%;
  }
  .el-upload-dragger {
    width: 100% !important;
    height: 200px !important;
  }
  .el-select .el-select--small {
    display: block !important;
  }
  .el-upload-dragger .el-icon-upload {
    // line-height: 300px !important;
  }
  .el-upload-list .el-upload-list--text {
    height: 360px;
    overflow: auto;
  }
</style>

<!-- 页面布局-->
<template>
  <div class="table">
    <!-- 主体区 -->
    <div class="container">
      <!-- 表单区 -->
      <div class="form-data-box">
        <el-form
          :model="formBean"
          :rules="validateRules"
          ref="form1"
          label-width="0px"
          class="ruleForm"
          style="width: 80%;"
        >
          <el-row style="margin-top: 18px;">
            <el-col :span="24">
              <el-form-item label prop>
                <div class="fxrow">
                  <el-upload
                    class="upload-demo common"
                    action
                    drag
                    multiple
                    :http-request="uploadFile"
                    show-file-list
                    :file-list="fileList"
                    :on-remove="handleRemove"
                    :on-change="handleFileChange"
                    accept=".zip"
                  >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text upload-demo">
                      将文件拖到此处，或
                      <em>选择文件</em>
                      <div class="el-upload__tip" slot="tip">
                        只能上传zip文件
                      </div>
                    </div>
                  </el-upload>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0" style="position:absolute;top:340px">
            <el-col :span="24">已选择文件列表：</el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 表单区END -->
      <!-- 按钮操作区 -->
      <span slot="footer" class="form-btn-box">
        <!-- <el-button v-if="!readOnly" @click="resetForm">重 置</el-button> -->
        <el-button v-if="!readOnly" type="primary" @click="toSubmit()"
          >导 入</el-button
        >
        <el-button @click="cnacelForm('form1')">取 消</el-button>
      </span>
      <!-- 按钮操作区END -->
    </div>
    <!-- 主体区END -->
  </div>
</template>
<script>
  export default {
    data() {
      return {
        // 提交表单的loading设置标识
        fullscreenLoading: false,
        firstLoadedData: "{}",
        // 新增用户表单信息
        formBean: {
          operateFileName: "", //上传图片
        },
        orgNotsele: true,
        // 表单校验规则
        validateRules: {
          operateFileName: [
            { required: true, message: "请上传文件", trigger: "blur" },
          ],
        },
        //所选记录id
        selectedId: "",
        //事物类型
        actType: "",
        // 表单只读状态
        readOnly: false,
        readOnlyEdt: false,
        //字典集
        dicts: {},
        cascaders: {},
        cascaderSelected: {},
        updimgurl: "",
        showTable: false,
        // 查询出的表格数据
        tableData: [],
        fileList: [],
        downloadFileUrl: "",
        // 筛选条件
        parampters: {
          //查询参数
          pageRows: 8, //每页行数
          pageIndex: 1, //当前页
          pageCount: 0, //总页数
          totalCount: 0, //总记录数
          province: null,
          city: null,
          provinceCode: "",
          provinceName: "",
          cityCode: "",
          cityName: "",
          productName: "",
          dnsegNum: "",
          cardFaceName: "",
          starttime: "",
          endtime: "",
        },
        previewId: "",
        files: [],
        uploadForm: null,
      };
    },
    props: {
      sourceData: {
        required: true,
      },
    },
    // 进入页面加载数据
    mounted() {
      this.handleInitLoad();
    },
    methods: {
      /**
       * 组件初始化加载
       */
      handleInitLoad() {
        this.uploadForm = new FormData();
        // this.initFormData();
        // this.getDownloadSampleUrl();
      },

      /**
       * 取消返回
       * @augments formName 表单名称
       */
      cnacelForm(formName) {
        this.$refs[formName].resetFields();
        this.$emit("cancel", this.cancelData);
      },
      /**
       * 重置表单
       * @augments formName 表单名称
       */
      resetForm(formName) {
        this.formBean.operateFileName = "";
        this.files = [];
      },
      /**
       *初始化加载表单数据
       */
      initFormData() {
        this.selectedId = this.sourceData.seleid;
        this.actType = this.sourceData.actType;
        this.readOnlyEdt = true;
        if (this.actType == "view") {
          // 查看状态 标识表单只读
          this.readOnly = true;
        } else if (this.actType == "add") {
          this.readOnly = false;
          this.readOnlyEdt = false;
          //清空修改保存之后数据还存在的情况
          for (var key in this.formBean) {
            this.formBean[key] = "";
          }
        } else {
          this.readOnly = false;
        }
        if (this.$util.getLoginer().administrator == true) {
          this.orgNotsele = false;
        } else {
          this.orgNotsele = true;
        }
        var url = "/herp/cardFace/";
        if (
          this.actType != null &&
          (this.actType == "upd" || this.actType == "view")
        ) {
          url += this.selectedId + "/";
          this.$axios
            .get(
              url,
              {
                params: {},
              },
              {
                headers: {
                  operator: this.$util.getLoginer().userid,
                  withCredentials: true,
                },
              }
            )
            .then((res) => {
              let data = res.data;
              if (data.success) {
                this.formBean = data.data;
                this.firstLoadedData = JSON.stringify(this.formBean);
              } else {
                this.$error(data.message);
              }
            })
            .catch((err) => {});
        }
      },

      /**
       * 下载excle模板
       */
      getDownloadSampleUrl() {
        this.$axios
          .get("/herp/cardApplyBatch/template/export/", {})
          .then((res) => {
            let data = res.data;
            if (data.success) {
              this.downloadFileUrl = data.data;
            }
          })
          .catch((err) => {
            console.log(err);
          });
      },

      /**
       * 提交表单
       * @augments formName 表单名称
       */
      submitForm(e) {
        //
        this.$refs["form1"].validate((valid) => {
          if (valid) {
            // 表单校验成功
            if (this.actType == "add") {
              if (!this.showTable) {
                this.$error("文件预览失败，不支持提交");
                return;
              }
              var url = "/herp/cardApplyPreview/" + this.previewId + "/";
              //
              // 开启提交表单的loading
              this.fullscreenLoading = true;
              this.$axios
                .post(
                  url,
                  {},
                  {
                    headers: {
                      operator: this.$util.getLoginer().userid,
                      withCredentials: true,
                    },
                  }
                )
                .then((res) => {
                  let data = res.data;
                  // 关闭提交表单的loading
                  this.fullscreenLoading = false;
                  if (data.success) {
                    this.$message({
                      message: "申请保存成功",
                      type: "success",
                    });
                    this.$emit("ok", {});
                  } else {
                    this.$error(data.message);
                  }
                })
                .catch((err) => {
                  this.fullscreenLoading = false;
                });
            }
          } else {
            // 表单校验失败
            // this.$error("数据校验失败.");
          }
        });
      },

      handleFileChange(file, fileList) {
        // this.fileList = fileList.slice(-1);
      },

      /**
       * 上传excel文件
       */
      uploadFile(params) {
        this.files.push(params.file);
        // this.toSubmit();
      },
      handleRemove(file, fileList) {
        let a = this.files.filter((item, i) => {
          return item.uid != file.uid;
        });
        this.files = a;
        console.log("tag", this.files);
      },
      toSubmit() {
        this.uploadForm = new FormData();
        this.$util.loadingshow();
        this.files.forEach((item, index) => {
          this.uploadForm.append("files", item);
        });
        console.log("tag", this.uploadForm);
        //  .post("/herp/mca/importMulti/", this.uploadForm, {
        this.$axios
          .post("/herp/cardApplyResp/importMulti/", this.uploadForm, {
            headers: {
              operator: this.$util.getLoginer().userid,
              withCredentials: true,
            },
          })
          .then((res) => {
            this.$util.loadinghide();
            let data = res.data;
            if (data.success) {
              this.$message({
                type: "success",
                message: data.message,
              });
              this.$emit("ok", {});
            } else {
              this.$error(data.message);
            }
          })
          .catch((err) => {
            this.$util.loadinghide();
            console.log(err);
          });
      },

      downloadFile() {
        let downloadUrl = this.downloadFileUrl;
        let n = downloadUrl.split("/");
        var link = document.createElement("a");
        //设置下载的文件名
        link.download = n[n.length - 1];
        link.style.display = "none";
        //设置下载路径
        link.href = downloadUrl;
        //浏览器兼容，禁止打开新的页面
        link.target = "_self";
        //触发点击
        document.body.appendChild(link);
        link.click();
        //移除节点
        document.body.removeChild(link);
      },
    },
  };
</script>
